package com.kingyea.app.market.appBaseInfo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kingyea.app.market.Preconditions;
import com.kingyea.app.market.apiInterface.service.ApiInterfaceService;
import com.kingyea.app.market.appBaseInfo.bean.*;
import com.kingyea.app.market.appBaseInfo.service.AppBaseInfoService;
import com.kingyea.app.market.appBaseInfo.vo.AppBaseInfo2CreatePageInputVO;
import com.kingyea.app.market.appExtendInfo.bean.AppExtendInfo;
import com.kingyea.app.market.appExtendInfo.service.AppExtendInfoService;
import com.kingyea.app.market.auth.bean.Authorize;
import com.kingyea.app.market.authorize.service.AuthorizeService;
import com.kingyea.app.market.client.MarketServiceClient;
import com.kingyea.app.market.client.OrganizationServiceClient;
import com.kingyea.app.market.client.UserServiceClient;
import com.kingyea.app.market.condition.AllCondition;
import com.kingyea.app.market.dept.bean.AuthDeptVo;
import com.kingyea.app.market.dept.bean.Organization;
import com.kingyea.app.market.market.bean.Market;
import com.kingyea.app.market.publishMarket.bean.PublishMarket;
import com.kingyea.app.market.publishMarket.service.PublishMarketService;
import com.kingyea.app.market.syncMission.bean.SyncMission;
import com.kingyea.app.market.syncMission.bean.SyncMission.PushStatus;
import com.kingyea.app.market.syncMission.service.SyncMissionService;
import com.kingyea.app.market.utils.BasePage;
import com.kingyea.app.market.utils.GlobalVar;
import com.kingyea.app.market.utils.StateCode;
import com.kingyea.app.market.utils.page.PageInfo;
import com.kingyea.app.market.versionInfo.bean.VersionInfo;
import com.kingyea.app.market.versionInfo.bean.VersionInfoVo;
import com.kingyea.app.market.versionInfo.service.VersionInfoService;
import com.kingyea.mobilepolice.system.Result;
import com.kingyea.mobilepolice.system.aspect.NotResult;
import com.kingyea.mobilepolice.system.exception.BusinessException;
import com.kingyea.mobilepolice.system.job.GlobalJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author
 * @version v1.0.0
 * @description AppBaseInfo 控制层
 * @date Created in 2018-02-09 17:34:59
 */
@RequestMapping(value = "/appBaseInfo")
@RestController
@Transactional
public class AppBaseInfoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppBaseInfoController.class);
    public static LinkedBlockingQueue<Map<String, Object>> toBeSycQueue = new LinkedBlockingQueue<>();
    @Autowired
    private AppBaseInfoService appBaseInfoService;
    @Autowired
    private AppExtendInfoService appExtendInfoService;
    @Autowired
    private PublishMarketService publishMarketService;
    @Autowired
    private ApiInterfaceService apiInterfaceService;
    @Autowired
    private MarketServiceClient marketServiceClient;
    @Autowired
    private VersionInfoService versionInfoService;
    @Autowired
    private SyncMissionService syncMissionService;
    @Autowired
    private OrganizationServiceClient organizationServiceClient;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * 查询全部
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object list(@RequestBody Map<String, Object> appBaseInfo) throws Exception {
        return appBaseInfoService.list(appBaseInfo);
    }

    /**
     * 获取应用版本信息
     *
     * @param appBaseInfo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/versionList", method = RequestMethod.POST)
    public Object versionList(@RequestBody Map<String, Object> appBaseInfo) throws Exception {
        return appBaseInfoService.versionList(appBaseInfo);
    }

    /**
     * 获取应用信息 丽姐写的
     *
     * @param appBaseInfo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/appList", method = RequestMethod.POST)
    public Object appList(@RequestBody Map<String, Object> appBaseInfo) throws Exception {
        return appBaseInfoService.appList(appBaseInfo);
    }

    /**
     * 获取应用信息
     *
     * @param appBaseInfo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/appList_new", method = RequestMethod.POST)
    public Object appList_new(@RequestBody Map<String, Object> appBaseInfo) throws Exception {
        return appBaseInfoService.appList_new(appBaseInfo);
    }

    /**
     * 应用列表展示
     *
     * @param appBaseInfo
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    public Object getList(@RequestBody Map<String, Object> appBaseInfo) {
        Object list = null;
        try {
            list = appBaseInfoService.getList(appBaseInfo);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 通过ID查找对象
     *
     * @param appCode
     * @return
     */
//    @RequestMapping(value = "/{appCode}", method = RequestMethod.GET)
//    public AppBaseInfo detail(@PathVariable String appCode) throws Exception {
//        return appBaseInfoService.getById(appCode);
//    }
    @RequestMapping(value = "/listInfo", method = RequestMethod.POST)
    public Object listInfo(@RequestBody Map<String, Object> appBaseInfo) {
        Object list = null;
        try {
            list = appBaseInfoService.listInfo(appBaseInfo);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 通过应用分类 查找
     *
     * @param classCode
     * @return
     */
    @RequestMapping(value = "/appType/{classCode}", method = RequestMethod.GET)
    public Object getByAppType(@PathVariable String classCode) {
        return appBaseInfoService.getByAppType(classCode);

    }

    /**
     * 通过应用市场 查找
     *
     * @param marketCode
     * @return
     */
    @RequestMapping(value = "/market/{marketCode}", method = RequestMethod.GET)
    public Object getByMarket(@PathVariable String marketCode) {
        List<AppBaseInfo> byMarket = null;
        try {

            byMarket = appBaseInfoService.getByMarket(marketCode);
        } catch (Exception e) {
        }
        return byMarket;

    }

    /**
     * 新增应用
     * 目前逻辑兼容更新逻辑
     *
     * @param appBaseInfo2CreatePageInputVO
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Object create(@RequestBody AppBaseInfo2CreatePageInputVO appBaseInfo2CreatePageInputVO) throws Exception {
        return appBaseInfoService.addApp(appBaseInfo2CreatePageInputVO);// 事务相关，所以移到了service
    }

    /**
     * 更新
     *
     * @param appBaseInfo
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(@RequestBody AppBaseInfo appBaseInfo) throws Exception {
        if (!StringUtils.isEmpty(appBaseInfo.getPublishFlag())) {

            if (appBaseInfo.getPublishFlag() == 1) {
                //应用 已发布，修改应用信息  需产生同步任务,（只更新应用信息，不带版本，只产生一条同步任务）
                SyncMission syncMission = new SyncMission();
                syncMission.setAppCode(appBaseInfo.getAppCode());
                syncMission.setMarketCode(appBaseInfo.getMarketCode());
                syncMission.setStatus(PushStatus.waiting);
                syncMission.setStartDate(new Date(System.currentTimeMillis()));
                syncMissionService.save(syncMission);
            }
        }
        appExtendInfoService.update(appBaseInfo.getExtendMap());
        return appBaseInfoService.update(appBaseInfo);
    }

    /**
     * 发布接口
     * 同步作业
     *
     * @param appBaseInfo ｛包含app信息，包含需要发布的市场id，包含是否同步作业标记(主要是防止同步作业之间死循环调用)｝
     * @return
     * @throws Exception
     */
    @SuppressWarnings({"unchecked", "null"})
    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    public Object publish(@RequestBody Map<String, Object> appBaseInfo) throws Exception {
//    	if(如果需要同步){
        toBeSycQueue.offer(appBaseInfo);
//    	}
        System.out.println(JSON.toJSONString(appBaseInfo));
        Object appObj = appBaseInfo.get("app");
//    	Object marketListObj = appBaseInfo.get("market");
        AppBaseInfo baseInfo = null;// app 信息
        VersionInfo webVersionObj = null;
        VersionInfo iosVersionObj = null;
        VersionInfo androidVersionObj = null;
        List<Object> marketObjList = new ArrayList<>();
        List<Market> marketList = new ArrayList<>();
//    	try{
        baseInfo = JSON.parseObject(JSON.toJSONString(appObj), AppBaseInfo.class);
        baseInfo.setPublishFlag(1);
        baseInfo.setPublishDate(new Date());
        AppBaseInfo update = appBaseInfoService.update(baseInfo);
        //记录推送状态
        Object marketListObj = appBaseInfo.get("marketList");
        marketObjList = JSON.parseObject(JSON.toJSONString(marketListObj), List.class);
        for (Object object : marketObjList) {//遍历市场
            Market market = JSON.parseObject(JSON.toJSONString(object), Market.class);
            if (GlobalJob.isIsInit() && (GlobalVar.marketCode.equals(market.getMarketCode()))) {/// 跳过管理市场

            } else {
                SyncMission syncMission = new SyncMission();
                syncMission.setAppCode(baseInfo.getAppCode());
                syncMission.setMarketCode(market.getMarketCode());
                syncMission.setStatus(PushStatus.waiting);
                syncMission.setStartDate(new Date(System.currentTimeMillis()));
//    			for (int i = 0; i < 3; i++) {
                if (appBaseInfo.containsKey("ver1")) {
                    Object webObj = appBaseInfo.get("ver1");
                    webVersionObj = JSON.parseObject(JSON.toJSONString(webObj), VersionInfo.class);
                    syncMission.setVersion(webVersionObj.getVersion());
                    syncMission.setVersionType(webVersionObj.getVersionType());
                    syncMissionService.save(syncMission);
                }
                if (appBaseInfo.containsKey("ver2")) {
                    Object iosObj = appBaseInfo.get("ver2");
                    iosVersionObj = JSON.parseObject(JSON.toJSONString(iosObj), VersionInfo.class);
                    syncMission.setVersion(iosVersionObj.getVersion());
                    syncMission.setVersionType(iosVersionObj.getVersionType());
                    syncMissionService.save(syncMission);
                }
                if (appBaseInfo.containsKey("ver3")) {
                    Object androidObj = appBaseInfo.get("ver3");
                    androidVersionObj = JSON.parseObject(JSON.toJSONString(androidObj), VersionInfo.class);
                    syncMission.setVersion(androidVersionObj.getVersion());
                    syncMission.setVersionType(androidVersionObj.getVersionType());
                    syncMissionService.save(syncMission);
                }
            }
//				}
        }
//    		marketObjList = JSON.parseObject(JSON.toJSONString(marketListObj), List.class);
//    		for (Object object : marketObjList) {
////    			Map<String, Object> marketObjMap = JSON.parseObject(JSON.toJSONString(object),Map.class);
////    			// 转换子对象 ApplicationType 应用类型
////    			ApplicationType appType = JSON.parseObject(JSON.toJSONString(marketObjMap.get("clazz")),ApplicationType.class) ;
////    			// 移除子对象防止转换报错
////    			marketObjMap.remove("clazz");
//
//    			Market market = JSON.parseObject(JSON.toJSONString(object),Market.class);
//    			if (baseInfo.getAppMarket()=="") {
//					// todo 默认应用市场关联字段被删除，暂时不知道怎么操作 03/20
//				}else if(market.getMarketCode()==baseInfo.getAppMarket()){//本地市场   if(需要发布的市场列表.是否包含(本地市场:从配置文件获取))
//    			}else{// 如果还有其他市场
//					appBaseInfo.put("syncFlag", "true");
//				}
////    			market.setClazz(appType);
//    			marketList.add(market);
//    			System.out.println(marketList);
//			}

//    	}catch(Exception e){
//    		e.printStackTrace();
//    		throw new BusinessException(StateCode.ILLEGAL_ARGUMENT_ERROR, StateCode.getMsg(StateCode.ILLEGAL_ARGUMENT_ERROR));
//    	}
//    	System.out.println("appmarketID: "+baseInfo.getAppMarket());
//    	System.out.println(baseInfo);
        // 判断该应用使用是否是本市场的，是的话就先本市场发布app
        // 获取需要同步市场(参数带过来的)，如果存在其他需要发布的市场 && 不存在同步作业标记，那就通过HttpUtil发送到对应市场的“发布接口”
//    	if(true){
//
//    	}
        return update;
    }

    /**
     * 同步任务接收接口：
     * 系统角色为：  内网应用市场模式
     *
     * @throws Exception
     */
    @RequestMapping(value = "/doSync", method = RequestMethod.POST)
    public Object syncInterface(@RequestBody List<SyncObjVo> appInfoVoList) throws Exception {
        if (GlobalJob.isIsInit() && (GlobalVar.adminMarket == null || GlobalVar.adminMarket.intValue() != 1) && (GlobalVar.marketClassify != null && GlobalVar.marketClassify.intValue() == 3)) {
            Preconditions.checkNotNull(appInfoVoList, StateCode.NO_ARGUMENT_ERROR);

            Map<String, Object> marketMapParam = Maps.<String, Object>newHashMap();
            marketMapParam.put("marketClassify", 3);
            Result<PageInfo<Market>> marketListJsonStr = marketServiceClient.conditionQuery(marketMapParam);
            List<Market> marketList = marketListJsonStr.getData().getList();
            // TODO 是内网应用
            Preconditions.checkArgument(marketList != null && marketList.size() > 0, StateCode.NO_OPEN_ERROR);

            List<AppInfoVo> successAppInfoVoList = com.google.common.collect.Lists.<AppInfoVo>newArrayList();
            List<AppInfoVo> failAppInfoVoList = com.google.common.collect.Lists.<AppInfoVo>newArrayList();
            for (SyncObjVo appInfoVo : appInfoVoList) {
                try {
                    appBaseInfoService.save(appInfoVo);
//                    Map<String, Object> versionMap = Maps.newHashMap();
//                    versionMap.put("appCode", appInfoVo.getAppCode());
//                    versionMap.put("versionType", appInfoVo.getVersionInfo().getVersionType());
//                    versionMap.put("versionCode", appInfoVo.getVersionInfo().getVersion());
//					PageInfo versionPageInfo = (PageInfo)versionInfoService.list(versionMap);
//                    if(versionPageInfo.getTotal() == 0) {//已存在版本数据
//                        appBaseInfoService.save(appInfoVo);//保存应用信息
//                    }
                    AppInfoVo vo = new AppInfoVo();
                    vo.setSyncMissionId(appInfoVo.getSyncMission().getId());
					/*vo.setAppCode(appInfoVo.getAppCode());
					vo.setMarketCode(appInfoVo.getMarket().getMarketCode());
					vo.setVersionCode(appInfoVo.getVersionMap().get(0).getVersion());*/
                    successAppInfoVoList.add(vo);
                } catch (Exception e) {
                    LOGGER.error("【接收失败】" + JSONObject.toJSONString(appInfoVo), e);

                    AppInfoVo vo = new AppInfoVo();
                    vo.setSyncMissionId(appInfoVo.getSyncMission().getId());
					/*vo.setAppCode(appInfoVo.getAppCode());
					vo.setMarketCode(appInfoVo.getMarket().getMarketCode());
					vo.setVersionCode(appInfoVo.getVersionMap().get(0).getVersion());*/
                    failAppInfoVoList.add(vo);
                }
            }
            AppVo appVo = new AppVo();
            appVo.setFailList(failAppInfoVoList);
            appVo.setSuccessList(successAppInfoVoList);

            return appVo;
        }
        return new Result(StateCode.SYSTEM_ERROR, "系统未初始化完成或者该市场不具备  同步任务接收 功能。");
    }


    /**
     * 同步任务被拉取：提供数据
     * 系统角色为：  控制台模式
     *
     * @throws Exception
     */
    @RequestMapping(value = "/searchSyncData", method = RequestMethod.POST)
    public Object searchSyncData(@RequestBody AppInfoVo appInfoVo) throws Exception {

        if (GlobalJob.isIsInit() && (GlobalVar.marketClassify != null && GlobalVar.marketClassify.intValue() == 3) && (GlobalVar.adminMarket != null && GlobalVar.adminMarket.intValue() == 1)) {
            Preconditions.checkNotNull(appInfoVo.getMarketCode(), StateCode.SYSTEM_ERROR);


            Map<String, Object> marketMapParam = Maps.<String, Object>newHashMap();
            marketMapParam.put("adminMarket", 1);
            LOGGER.info("查询管理平台市场信息..............");
            Result<PageInfo<Market>> marketResult = marketServiceClient.conditionQuery(marketMapParam);
            if (!marketResult.getCode().equals(StateCode.OPERATION_SUCCESS)) {
                throw new BusinessException(StateCode.SYNC_GET_DATE_ERROR);
            }
            List<Market> marketList = marketResult.getData().getList();

            // TODO 是管理端
            Preconditions.checkArgument(marketList != null && marketList.size() > 0, StateCode.NO_OPEN_ERROR);

//			SyncMission syncMission = new SyncMission();
//			syncMission.setStatus(PushStatus.waiting);
//			syncMission.setMarketCode(appInfoVo.getMarketCode());
//			List<SyncMission> list = syncMissionService.list(syncMission);//获取等待推送记录
            Map<String, Object> syncMap = new HashMap();
            syncMap.put("marketCode", appInfoVo.getMarketCode());
            List<SyncMission> pushResult = syncMissionService.getPushResult(syncMap);//获取  等待推送 & 推送失败  记录
            List<SyncObjVo> baseInfoVoList = Lists.newArrayList();
            if (pushResult.size() > 0) {
                for (SyncMission bean : pushResult) {//  bean 单条推送信息
                    // 更新推送状态
                    LOGGER.info("正在封装同步数据，请稍等....");
                    bean.setStatus(PushStatus.pushing);
                    syncMissionService.update(bean);
                    AppBaseInfo baseInfoObj = appBaseInfoService.getById(bean.getAppCode());//应用信息
                    AppExtendInfo extendObj = appExtendInfoService.getByAppCode(bean.getAppCode());//扩展信息
                    Map<String, Object> map = new HashMap();
                    map.put("version", bean.getVersion());
                    map.put("appCode", bean.getAppCode());
                    map.put("versionType", bean.getVersionType());
                    PageInfo<VersionInfo> versionListObj = (PageInfo<VersionInfo>) versionInfoService.list(map);
                    List<VersionInfo> versionList = versionListObj.getList();
//				versionList.get(0);
                    System.out.println(versionList.toString());
                    syncMissionService.getById(bean.getId());
                    SyncObjVo objVo = new SyncObjVo();
                    if (versionList.size() == 1) {
//					VersionInfo versionInfoObj = (VersionInfo)versionList;//版本信息
                        //封装应用   基础信息，扩展信息，版本信息，推送记录（以更新推送状态）
                        objVo.setAppBaseInfo(baseInfoObj);
                        objVo.setAppExtendInfo(extendObj);
                        objVo.setVersionInfo(versionList.get(0));
                        objVo.setSyncMission(bean);
                    } else {
                        System.out.println("请检查应用是否存在或是否版本冲突....");
                    }
//				map.put("marketCode", bean.getMarketCode());
//				AppSyncBaseInfo baseInfo = appBaseInfoService.getSyncList(map);//获取需推送app相关信息
//				if(baseInfo != null){
//					baseInfo.setSyncMissionId(bean.getId());
//					baseInfo.setMarketCode(bean.getMarketCode());
//					baseInfo.setVersionCode(bean.getVersion());
//				}
                    baseInfoVoList.add(objVo);
                }
                LOGGER.info("成功封装同步数据....");
                System.out.println("=========================================================提供给拉取的数据");
                System.out.println(JSON.toJSONString(baseInfoVoList));
            } else {
                LOGGER.info("暂无同步数据需要封装....");
            }
            return baseInfoVoList;
        } else {
            return new Result(StateCode.SYSTEM_ERROR, "该模式无法提供数据,或系统有误", null);
        }

    }


    @NotResult
    @PostMapping("/notify")
    public Object synNotify(@RequestBody AppVo appVo) throws Exception {
        return updateNotify(appVo);
    }

    private boolean updateNotify(AppVo appVo) throws Exception {
        List<AppInfoVo> successList = appVo.getSuccessList();
        for (AppInfoVo app : successList) {
            SyncMission syncMission = new SyncMission();
            syncMission.setId(app.getSyncMissionId());
            /*syncMission.setAppCode(app.getAppCode());
            syncMission.setVersion(app.getVersionCode());
            syncMission.setMarketCode(app.getMarketCode());*/
            syncMission.setStatus(PushStatus.pushSuccess);
            syncMissionService.update(syncMission);
            LOGGER.info("【推送成功！！】");
        }

        List<AppInfoVo> failList = appVo.getFailList();
        for (AppInfoVo app : failList) {
            SyncMission syncMission = new SyncMission();
            syncMission.setId(app.getSyncMissionId());
           /* syncMission.setAppCode(app.getAppCode());
            syncMission.setVersion(app.getVersionCode());
            syncMission.setMarketCode(app.getMarketCode());*/
            syncMission.setStatus(PushStatus.pushFailure);
            syncMissionService.update(syncMission);
            LOGGER.info("【推送失败！！】");
        }
        return true;
    }


    /**
     * 同步业务处理
     *
     * @return
     * @throws Exception
     */
    public Object sycFunc(AppInfoVo appInfoVo) throws Exception {
        // 需要判断拿到的同步记录是 1、2、3 类型的市场
        Map<String, Object> market = new HashMap<>();
        try {
            market.put("localMarket", 1);//每个部署市场 只存在一个 本地市场
            Market singleMarket = null;//(Market)marketServiceClient.conditionQuery(market);//获取本地市场记录

            if (singleMarket.getAdminMarket() == 1) {//管理平台
                //to do nothing

            } else if (singleMarket.getMarketClassify() == appInfoVo.getMarket().getMarketClassify()) {//本地市场分类singleMarket.getMarketClassify()  == 接收对象的市场分类
                appBaseInfoService.save(appInfoVo);
                appExtendInfoService.save(appInfoVo.getExtendMap());//
                versionInfoService.save(appInfoVo.getVersionMap().get(0));
                //    	修改同步状态
//    		SyncMission syncMission = new SyncMission();
//    		syncMission =(SyncMission) appInfoVo.getSyncMissions();
//    		syncMission.setStatus(PushStatus.pushSuccess);
//    		syncMissionService.update((SyncMission)appInfoVo.getSyncMissions());

            }
        } catch (Exception e) {
            //同步失败
//			SyncMission syncMission = new SyncMission();
//			syncMission =(SyncMission) appInfoVo.getSyncMissions();
//			syncMission.setStatus(PushStatus.pushFailure);
//			syncMissionService.update((SyncMission)appInfoVo.getSyncMissions());
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//基础信息
        return true;
    }


    /**
     * 删除
     *
     * @param appCode
     * @return
     */
    @RequestMapping(value = "/{appCode}", method = RequestMethod.DELETE)
    public Object delete(@PathVariable String appCode) throws Exception {
        return appBaseInfoService.deleteById(appCode);
    }

    /**
     * 删除
     *
     * @param appCode
     * @return
     */
    @RequestMapping(value = "/deleteAllAppInfo/{appCode}", method = RequestMethod.DELETE)
    public Object deleteAllAppInfoByAppCode(@PathVariable String appCode) throws Exception {
        return appBaseInfoService.deleteAllAppInfoByAppCode(appCode);
    }

    @NotResult
    @GetMapping(value = "/test")
    public Object test(Map<String, Object> map) throws Exception {
        return appBaseInfoService.getSyncList(map);
    }

    /**
     * 部门授权列表封装
     *
     * @param map
     * @return
     * @throws Exception
     */
    @NotResult
    @RequestMapping(value = "/deptFromAuth", method = RequestMethod.POST)
    public Object getDeptListFromAuth(@RequestBody Map<String, Object> map) throws Exception {
        ArrayList<AuthDeptVo> arrayList = new ArrayList<AuthDeptVo>();
//		map.put("pageNo", map.get("pageNum"));
//		OrganizationCondition organizationCondition = new OrganizationCondition();
//		int pageNo = (int)map.get("pageNo");
//		int pageSize = (int)map.get("pageSize");
        Result<BasePage<Organization>> authDept = organizationServiceClient.authDept(map);
//		List<Organization> organizationLists = JSON.parseArray(JSON.toJSONString(authDept).toString(), Organization.class);
//		JSON.parseArray(JSON.toJSONString(authDept).toString(), Organization.class);
        PageInfo.startPage(map);
//		PageInfo pageInfo = PageInfo.getPageInfo(organizationLists);
        List<Organization> organizationLists = authDept.getData().getList();
        for (Organization organization : organizationLists) {
            AuthDeptVo authDeptVoObj = new AuthDeptVo();
            Map<String, Object> searchMap = new HashMap();
            searchMap.put("dept", organization.getOrgSerialNo());
            searchMap.put("appCode", map.get("appCode"));
            List<Authorize> list = authorizeService.list(searchMap);
            if (list.size() == 0) {
                authDeptVoObj.setIsAuth(false);
            } else if (list.size() == 1) {
                authDeptVoObj.setIsAuth(true);
            } else {
                LOGGER.debug("【系统异常】-----------------------------------");
            }
            authDeptVoObj.setAppCode(map.get("appCode").toString());
            authDeptVoObj.setOrganization(organization);
            arrayList.add(authDeptVoObj);
//			System.out.println(list.toString());
        }
        PageInfo<Object> pageInfo = new PageInfo<>();
        pageInfo.setList(arrayList);
        pageInfo.setPageNum(authDept.getData().getPageNum());
        pageInfo.setPageSize(authDept.getData().getPageSize());
        pageInfo.setTotal(authDept.getData().getTotal());
        return pageInfo;
//		System.out.println(arrayList.toString());
//		return PageInfo.getPageInfo(arrayList);
    }

    @NotResult
    @PostMapping("/publish/search")
    public Object searchPublishApp(@RequestBody AllCondition condition) throws Exception {
        PageInfo<AppBaseInfoPublishVo> appBaseInfoVoPage = appBaseInfoService.searchPpublishApp(condition);
        if (appBaseInfoVoPage.getList().size() > 0) {
            List<AppBaseInfoPublishVo> appBaseInfoVoList = appBaseInfoVoPage.getList();
            appBaseInfoVoList.stream().forEach(appVo -> {
                //注入版本信息
//				//版本类型 1：web,2:ios3:android //操作类型 1应用发布 2版本更新
                List<VersionInfoVo> versionInfoVoList = Stream.of(
                        appVo.getWeb(),
                        appVo.getIos(),
                        appVo.getAndroid()
                ).filter(org.apache.commons.lang3.StringUtils::isNotBlank).map(id -> versionInfoService.getById(id)).filter(versionInfo -> versionInfo != null).map(versionInfo -> {
                    VersionInfoVo vo = new VersionInfoVo();
                    BeanUtils.copyProperties(versionInfo, vo);
                    return vo;
                }).collect(Collectors.toList());
                appVo.setVersionInfoVos(versionInfoVoList);
                //如果是更新操作 注入旧版本信息
                if (appVo.getOperateType() == 2) {
                    versionInfoVoList.stream().forEach(vo -> {
                        //TODO 设置旧版本数据,查询当前版本
                        VersionInfo oldVer = versionInfoService.getCurrentVersionByAppCode(vo.getAppCode(), vo.getVersionType());
                        Optional.ofNullable(oldVer).ifPresent(last -> vo.setNewVersionInfo(last));

                        //TODO 设置旧版本数据,查询同步表根据条件拉去最后一条数据
//						SyncMissionService
						/*AllCondition syncCondition = new AllCondition();
						syncCondition.setMarketCodeStr(String.valueOf(appVo.getMarketCode()));
						syncCondition.setAppCode(vo.getAppCode());
						syncCondition.setVersionType(vo.getVersionType());
                        List<SyncMission> syncMissionList = syncMissionService.search(syncCondition).getList();
							if(syncMissionList.size() > 0) {
                            SyncMission lastSyncVersion = syncMissionList.get(0);
                            Optional.ofNullable(lastSyncVersion).map(SyncMission::getVersion).ifPresent(lastVersionInfoId -> {
                                Optional.ofNullable(versionInfoService.getById(lastVersionInfoId)).ifPresent(last -> vo.setNewVersionInfo(last));
                            });
                        }*/
                    });
                }
            });
        }
        return appBaseInfoVoPage;
    }

    @PostMapping("/verify")
    public Object verify(@RequestBody PublishMarket publishMarketVO) throws Exception {
        Preconditions.checkNotNull(publishMarketVO.getStatus(), StateCode.NO_ARGUMENT_ERROR);
        Preconditions.checkStringNotBlank(publishMarketVO.getId(), StateCode.NO_ARGUMENT_ERROR);
        PublishMarket publishMarket_ = publishMarketService.getById(publishMarketVO.getId());
        Preconditions.checkNotNull(publishMarket_, StateCode.NO_ARGUMENT_ERROR);
//		状态：0.待审核 1.审核通过 2.审核不通过
//		操作类型 1应用发布 2版本更新
        if (publishMarketVO.getStatus() == 1 && publishMarket_.getOperateType() == 1) {
            Preconditions.checkArgument(publishMarketService.publicMarket(publishMarket_), StateCode.SYSTEM_ERROR);
        } else if (publishMarketVO.getStatus() == 1 && publishMarket_.getOperateType() == 2) {
            Preconditions.checkArgument(publishMarketService.updateMarket(publishMarket_), StateCode.SYSTEM_ERROR);
        }
        publishMarket_.setStatus(publishMarketVO.getStatus());
        publishMarket_.setRemark(publishMarketVO.getRemark());
        return publishMarketService.update(publishMarket_);
    }

    @NotResult
    @PostMapping("/publish/verify/search")
    public Object searchPublishVerify(@RequestBody AllCondition condition) throws Exception {
        return appBaseInfoService.searchPublishVerify(condition);
    }

}
